package com.gkey.base.aop;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.gkey.base.cache.UsualParameter;
import com.gkey.core.util.CharsTool;
import com.gkey.core.web.util.SessionUtil;

/**  
 * @Title: springmvc适配器_拦截.java
 * @Package com.gkey.sole.base.aop
 * @Description: TODO
 * @author GuoKey
 * @date 2016年5月31日 上午10:52:18
 * @version 1.0
 */
public class SecurityInterceptor extends HandlerInterceptorAdapter {
	
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
		
		Object o = SessionUtil.getSessionAttribute(request, UsualParameter.SESSION_USER);
		
		//String contextpath = request.getContextPath();
		//System.out.println("contextpath:---------------------:"+contextpath);
		//String servletpath = request.getServletPath();
		//System.out.println("servletpath:---------------------:"+servletpath);
		String uri = request.getRequestURI();
		//System.out.println("uri:---------------------:"+uri);
		String querystr = request.getQueryString();
		//System.out.println("querystr:---------------------:"+querystr);
		if(null == o && intercept(uri)){
			String returl = uri;
			
			if(CharsTool.isNotEmpty(querystr)){
				returl +="?"+querystr;
			}
			response.sendRedirect("/login?returl="+returl.replaceAll("&", "|"));
		}
		
		return super.preHandle(request, response, handler);
	}
	
	/**
	 * 
	 * @Description: 路径是否拦截方案
	 * @param uri
	 * @return   
	 * Boolean  
	 * @throws
	 * @author keyGuo
	 * @date 2016年8月10日 下午4:42:43
	 */
	protected Boolean intercept(String uri){
		if( "/".equals(uri)						//初始进入项目的路径
				 || uri.startsWith("/js/") 		//js的引用路径
				 || uri.startsWith("/img/") 	//显示logo、图片的路径
				 || uri.startsWith("/css/") 	//css样式的引用路径
				 || uri.startsWith("/tool/") 	//页面插件
				 || uri.startsWith("/login") 	//登陆
				 || uri.startsWith("/register")	//注册
				 || uri.startsWith("/error")	//错误页面
			){
			return false;			
		}		
		return true;
	}
	

}
